import React, { useState, useEffect, useImperativeHandle } from 'react';
import ConditionGroups from '../../../../components/Conditions/ConditionGroups';
import { getConditionGroupJson } from 'src/utils/json';
import { Message } from 'antd';
import '../index.less';

export default function ExecConditions(props) {
  const { isTxt = false, logs = null } = props; //新增两个属性、isTxt为true时，展示为纯文本；logs是日志命中情况的对象,默认null
  const [value, setValue] = useState(props.value);
  useEffect(() => {
    props.value.length > 0 && setValue(props.value);
  }, [props.value]);

  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (cb) => {
      const isValidate = validate(value); // 验证数据
      if (isValidate) {
        cb(value, null);
      } else {
        cb(value, true);
      }
    },
  }));

  function handleConditionsChange(value) {
    console.log(value);
    setValue(value);
  }

  // 验证数据
  function validate(value) {
    try {
      getConditionGroupJson(value);
      return value;
    } catch (error) {
      Message.warning(error);
      return false;
    }
  }

  return (
    <div className='add-conditions-wrap' id='add-conditions-wrap'>
      <ConditionGroups
        isOld={props.isOld}
        isCompare={props.isCompare}
        strategy_id={props.strategy_id}
        compareData={props.compareData}
        variable={props.variable}
        limitType={props.limitType}
        using_variables={props.using_variables}
        onChange={handleConditionsChange}
        value={value}
        operatorOptions={props.operator}
        disabled={props.disabled}
        strategyId={props.strategyId}
        isTxt={isTxt}
        logs={logs}
        isImportant={props.isImportant}
        modelId={props.modelId}
      />
    </div>
  );
}
